/**
 * Created by GSY on 16/11/16.
 * 用于图片预览,可以缩放、可变数量图片浏览
 */
(function () {

    var dmGalleryOpations;  //内部用选项
	/**
     *
     * @param options 初始化选项
     * title dialog标题
     * showButtons 是否显示按钮 默认false
     * canScale 是否可缩放图片 默认true
     *
     * data对象 {
     *   buttonText: 点击按钮的内容
     * }
     * @constructor
     */
    window.DmGallery = function (options) {

        this.showButtons = options.showButtons || false;
        this.canScale = options.canScale || true;
        dmGalleryOpations = options;
        screenWidth = window.screen.width;

    };

    var galleryBg;     //画廊背景
    var currentImg;    //当前图片
    var nextImg;       //下一张图片
    var lastImg;       //上一张图片
    var nextButton;    //下一张按钮
    var lastButton;    //上一张按钮
    var cancelButton;  //关闭按钮
    var currentIndex;  //当前图片索引
    var maxIndex;      //图片数量
    var imgsUrl;       //图片地址
    var screenWidth;   //屏幕宽度
	/**
     * 显示画廊
     * @param imgs 图片列队数组
     */
    DmGallery.prototype.show = function (imgs, index) {

        if (imgs && imgs.length) {

        } else {
            imgs = [];
        }
        if (isNaN(index)) {
            currentIndex = 0;
        } else {
            currentIndex = parseInt(index);
            if (currentIndex >= imgs.length) {
                currentIndex = 0;
            }
        }
        maxIndex = imgs.length - 1;
        imgsUrl = imgs;

        galleryBg = document.createElement('div');
        galleryBg.setAttribute('id', 'dmGalleryBg');
        galleryBg.setAttribute('class', 'dm-gallery-bg');
        galleryBg.onclick = hideGallery;

        var imgBg = document.createElement('div');
        imgBg.setAttribute('id', 'dmGalleryImgBg');
        imgBg.setAttribute('class', 'dm-gallery-img-bg');
        imgBg.addEventListener('touchstart', imgBgTouch, false);
        imgBg.addEventListener('touchmove', imgBgTouch, false);
        imgBg.addEventListener('touchend', imgBgTouch, false);

        galleryBg.appendChild(imgBg);

        currentImg = document.createElement('img');
        nextImg = document.createElement('img');
        lastImg = document.createElement('img');
        currentImg.setAttribute('class', 'dm-gallery-img current');
        nextImg.setAttribute('class', 'dm-gallery-img next');
        lastImg.setAttribute('class', 'dm-gallery-img last');
        if (imgs[0]) {
            currentImg.src = imgs[0];
        }
        if (imgs[1]) {
            nextImg.src = imgs[1];
        } else {
            nextImg.src = '';
        }
        imgBg.appendChild(currentImg);
        imgBg.appendChild(nextImg);
        imgBg.appendChild(lastImg);

        if (this.showButtons) {
            cancelButton = document.createElement('div');
            nextButton = document.createElement('div');
            lastButton = document.createElement('div');
            cancelButton.setAttribute('id', 'galleryCancelButton');
            nextButton.setAttribute('id', 'galleryNextButton');
            lastButton.setAttribute('id', 'galleryLastButton');
            cancelButton.setAttribute('class', 'dm-gallery-button cancel');
            nextButton.setAttribute('class', 'dm-gallery-button next');
            lastButton.setAttribute('class', 'dm-gallery-button last');
            nextButton.onclick = nextPhoto;
            lastButton.onclick = lastPhoto;
            galleryBg.appendChild(cancelButton);
            galleryBg.appendChild(nextButton);
            galleryBg.appendChild(lastButton);
        }

        document.body.appendChild(galleryBg);

    };

    function hideGallery(e) {
        if (e.target.nodeName === 'IMG' || e.target.id === 'galleryNextButton' || e.target.id === 'galleryLastButton') {
            return;
        } else if (galleryBg && galleryBg.parentNode) {
            galleryBg.parentNode.removeChild(galleryBg);
        }
    }

    DmGallery.prototype.hide = function () {
        galleryBg.parentNode.removeChild(galleryBg);
    };

    var lastTouchEnd;      //记录时间  用于判断双击事件
    var lastScale = 1.0;   //图片上次缩放大小
    var isScale = false;   //标记是否在捏合、放大
    var isSwipe = false;   //标记是否在左右滑动
    var moveStartX;        //移动事件开始的X坐标
    var moveStartY;        //移动事件开始的Y坐标
    var moveX;             //移动事件的X距离
    var moveY;             //移动事件的Y距离
    var totalMoveX = 0;    //当前图片移动X位置总量
    var totalMoveY = 0;    //当前图片移动Y位置总量
    var pinchStart;        //捏合手势初始线长
    var lastPinchScale;    //捏合手势结束前的缩放大小

    function imgBgTouch(event) {
        if (event.type === 'touchstart') {
            //触摸开始
            if (event.touches.length === 2) {
                var ps1 = event.touches[0];
                var ps2 = event.touches[1];
                pinchStart = (ps2.pageX - ps1.pageX) * (ps2.pageX - ps1.pageX) + (ps2.pageY - ps1.pageY) * (ps2.pageY - ps1.pageY);
                imgBgScale('gesturestart', 1.0);
            } else if (event.touches.length === 1) {
                currentImg.style.transition = 'none';
                nextImg.style.transition = 'none';
                lastImg.style.transition = 'none';
                lastImg.style.opacity = 0;
                nextImg.style.opacity = 0;
                moveStartX = event.touches[0].pageX;
                moveStartY = event.touches[0].pageY;
            }

        } else if (event.type === 'touchmove') {
            //触摸移动
            if (isScale) {
                if (event.touches.length === 2) {
                    var pm1 = event.touches[0];
                    var pm2 = event.touches[1];
                    var pinchMove = (pm2.pageX - pm1.pageX) * (pm2.pageX - pm1.pageX) + (pm2.pageY - pm1.pageY) * (pm2.pageY - pm1.pageY);
                    var scale = pinchMove / pinchStart;
                    lastPinchScale = scale;
                    imgBgScale('gesturechange', scale);
                }
                return;
            } else {
                isSwipe = true;
                moveX = totalMoveX + event.touches[0].pageX - moveStartX;
                moveY = totalMoveY + event.touches[0].pageY - moveStartY;

                if (moveX > 0) {
                    currentImg.style.left = 'calc(100vw + ' + moveX + 'px)';
                    lastImg.style.left = moveX + 'px';
                    nextImg.style.left = 'calc(200vw + ' + moveX + 'px)';
                } else {
                    currentImg.style.left = 'calc(100vw - ' + (-moveX) + 'px)';
                    lastImg.style.left = moveX + 'px';
                    nextImg.style.left = 'calc(200vw - ' + (-moveX) + 'px)';
                }

                if (lastScale !== 1.0) {
                    if (moveY > 0) {
                        currentImg.style.top = 'calc(50% + ' + moveY + 'px)';
                    } else {
                        currentImg.style.top = 'calc(50% - ' + (-moveY) + 'px)';
                    }
                }

            }

        } else if (event.type === 'touchend') {
            //触摸结束
            if (isScale) {
                console.log(event.touches);
                imgBgScale('gestureend', lastPinchScale);
                return;
            }
            currentImg.style.transition = 'all .2s linear';
            nextImg.style.transition = 'all .2s linear';
            lastImg.style.transition = 'all .2s linear';
            moveStartX = undefined;
            moveStartY = undefined;
            if (moveX) {
                totalMoveX = moveX;
            }
            if (moveY) {
                totalMoveY = moveY;
            }
            var movePer = Math.abs(totalMoveX) / window.screen.width * 100;
            if (lastScale >= 1 && movePer > (lastScale - 1) * 100 / 2 + 25) {
                //确认翻页
                confirmPage();
            } else if (lastScale < 1 && movePer > 0.25) {
                //确认翻页
                confirmPage();
            } else {
                //取消翻页
                if (lastScale == 1.0) {
                    moveX = undefined;
                    moveY = undefined;
                    totalMoveX = 0;
                    totalMoveY = 0;
                    currentImg.style.left = '100vw';
                    lastImg.style.left = '0';
                    nextImg.style.left = '200vw';
                }

            }

            if (lastTouchEnd && !isScale && !isSwipe) {
                var newTime = event.timeStamp;
                if (newTime - lastTouchEnd < 550) {
                    //间隔小于550  判定为双击
                    lastTouchEnd = undefined;
                    imgBgDblclick();
                } else {
                    lastTouchEnd = newTime;
                }

            } else {
                lastTouchEnd = event.timeStamp;
            }

            setTimeout(function () {
                isSwipe = false;
            }, 300);

        }
    }

    function imgBgScale(type, scale) {

        console.log(type + ': ' + scale);

        if (type === 'gesturestart') {

            lastTouchEnd = undefined;
            isScale = true;
            currentImg.style.transition = 'none';
            nextImg.style.transition = 'none';
            lastImg.style.transition = 'none';

        } else if (type === 'gesturechange') {

            currentImg.style.transform = 'translateY(-50%) scale(' + (lastScale * scale) + ')';

        } else if (type === 'gestureend') {
            
            currentImg.style.transition = 'all .2s linear';
            nextImg.style.transition = 'all .2s linear';
            lastImg.style.transition = 'all .2s linear';

            if (lastScale * scale > 3) {
                currentImg.style.transform = 'translateY(-50%) scale(3.0)';
                lastScale = 3.0;
            } else if (lastScale * scale < 0.5) {
                currentImg.style.transform = 'translateY(-50%) scale(.5)';
                lastScale = 0.5;
            } else {

                if (lastScale * scale > 0.8 && lastScale * scale < 1.2) {
                    currentImg.style.transform = 'translateY(-50%) scale(1.0)';
                    currentImg.style.top = '50%';
                    currentImg.style.left = '100vw';
                    totalMoveY = 0;
                    totalMoveX = 0;
                    lastScale = 1.0;
                } else {
                    currentImg.style.transform = 'translateY(-50%) scale(' + (lastScale * scale) + ')';
                    lastScale = lastScale * scale;
                }

            }

            setTimeout(function () {
                isScale = false;
                lastPinchScale = undefined;
            }, 100);

        }

    }

    function imgBgDblclick() {

        if (isSwipe || isScale) {
            //如果在进行翻页或缩放
            return;
        } else {
            currentImg.style.transition = 'all .2s linear';
            nextImg.style.transition = 'all .2s linear';
            lastImg.style.transition = 'all .2s linear';

            if (lastScale >= 1 && lastScale < 3) {
                //比例在1~3(包含1)时  比例设为3
                currentImg.style.transform = 'translateY(-50%) scale(3.0)';
                lastScale = 3.0;
            } else {
                //比例小于1或为3时  比例设为1
                currentImg.style.transform = 'translateY(-50%) scale(1.0)';
                currentImg.style.top = '50%';
                currentImg.style.left = '100vw';
                totalMoveY = 0;
                totalMoveX = 0;
                lastScale = 1.0;
            }
        }

    }

    function confirmPage() {
        //确认翻页
        totalMoveX = 0;
        totalMoveY = 0;
        lastImg.style.opacity = 100;
        nextImg.style.opacity = 100;
        currentImg.style.left = '';
        lastImg.style.left = '';
        nextImg.style.left = '';
        currentImg.style.top = '50%';
        lastImg.style.top = '50%';
        nextImg.style.top = '50%';
        if (moveX > 0) {
            //上一页
            lastPhoto();
        } else {
            //下一页
            nextPhoto();
        }
        moveX = undefined;
        moveY = undefined;
    }

    function nextPhoto() {
        //下一张图片
        if (currentIndex < maxIndex) {

            nextImg.style.opacity = 100;
            currentImg.style.transform = 'translateY(-50%) scale(1.0)';
            nextImg.style.transform = 'translateY(-50%) scale(1.0)';
            lastImg.style.transform = 'translateY(-50%) scale(1.0)';
            lastScale = 1.0;

            currentImg.style.transition = 'all .2s linear';
            nextImg.style.transition = 'all .2s linear';
            lastImg.style.transition = 'none';

            currentImg.setAttribute('class', 'dm-gallery-img last');
            nextImg.setAttribute('class', 'dm-gallery-img current');
            lastImg.setAttribute('class', 'dm-gallery-img next');

            var imgsDom = [currentImg, nextImg, lastImg];

            currentImg = imgsDom[1];
            nextImg = imgsDom[2];
            lastImg = imgsDom[0];

            currentIndex += 1;
            setLastAndNextImg();

        } else {
            nextImg.style.opacity = 0;
            return;
        }
    }

    function lastPhoto() {
        //上一张图片
        if (currentIndex > 0) {

            lastImg.style.opacity = 100;
            currentImg.style.transform = 'translateY(-50%) scale(1.0)';
            nextImg.style.transform = 'translateY(-50%) scale(1.0)';
            lastImg.style.transform = 'translateY(-50%) scale(1.0)';
            lastScale = 1.0;

            currentImg.style.transition = 'all .2s linear';
            nextImg.style.transition = 'none';
            lastImg.style.transition = 'all .2s linear';

            currentImg.setAttribute('class', 'dm-gallery-img next');
            nextImg.setAttribute('class', 'dm-gallery-img last');
            lastImg.setAttribute('class', 'dm-gallery-img current');

            var imgsDom = [currentImg, nextImg, lastImg];

            currentImg = imgsDom[2];
            nextImg = imgsDom[0];
            lastImg = imgsDom[1];

            currentIndex -= 1;
            setLastAndNextImg();

        } else {
            lastImg.style.opacity = 0;
            return;
        }
    }

    function setLastAndNextImg() {
        if (imgsUrl[currentIndex + 1]) {
            nextImg.src = imgsUrl[currentIndex + 1];
        } else {
            nextImg.src = '';
        }
        if (imgsUrl[currentIndex - 1]) {
            lastImg.src = imgsUrl[currentIndex - 1];
        } else {
            lastImg.src = '';
        }
    }

})();
